﻿using HZY.Quartz;
using HZY.Quartz.Common;
using Microsoft.AspNetCore.Hosting;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace HZY.Quartz.Service.Impl
{
    /// <summary>
    /// 文件数据服务
    /// </summary>
    public class FileDataService : IFileDataService
    {
        private readonly string _webRootPath;

        private string FilePath { get; set; }

        public FileDataService(IWebHostEnvironment webHostEnvironment)
        {
            _webRootPath = webHostEnvironment.WebRootPath;
        }

        public bool Init(string path)
        {
            FilePath = path;

            return true;
        }

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public async Task<IEnumerable<T>> ReadDataAsync<T>()
        {
            var path = this.GetPath();

            var data = await File.ReadAllTextAsync(path);

            if (string.IsNullOrWhiteSpace(data)) return default;

            return JsonConvert.DeserializeObject<IEnumerable<T>>(data);
        }

        /// <summary>
        /// 写入数据
        /// </summary>
        /// <returns></returns>
        public async Task<bool> WriteDataAsync<T>(T contents)
        {
            var path = this.GetPath();

            await File.WriteAllTextAsync(path, JsonConvert.SerializeObject(contents));

            return true;
        }


        #region 私有

        private string GetPath()
        {
            if (string.IsNullOrWhiteSpace(FilePath)) throw new MessageBox("属性 FilePath 空对象,请使用前调用 Init 函数!");

            var path = _webRootPath + FilePath;

            if (!File.Exists(path))
            {
                File.Create(path);
            }

            return path;
        }

        #endregion


    }
}
